const express = require('express');
const utility = require('utility');

const Router = express.Router();
const mysqlConnect = require('./mysqlConfig');

Router.get('/info', (req, res) => {
    const phone = req.cookies.userPhone;
    if(!phone){
        return res.json({code:1});
    }
    let sqlQuery = `select userName from users where phone =${phone}`;
    mysqlConnect.sql(sqlQuery,(err,rows,fields)=>{
        if(err){
            console.log(err);
            return res.json({code:2,msg:"服务器错误"});
        }
        if(rows.length>0){
            res.json({code:0,data:rows[0].userName});
        }
    });
});

//注册
Router.post('/register', function (req, res) {
    const {userPhone, userPassword} = req.body;
    let sqlQuery = `select * from users where phone = ${userPhone}`;
    mysqlConnect.sql(sqlQuery, (err, rows, fields) => {
        if (err) {
            console.log(err);
            return res.json({code: 2, msg: "服务器错误"});
        }
        if (rows.length > 0) {
            return res.json({code: 1, msg: "手机号已存在"});
        }
        let sqlQuery = `insert into users(userName,phone,password) value("${userPhone}","${userPhone}","${MD5PWD(userPassword)}")`;
        mysqlConnect.sql(sqlQuery, (err, rows, fields) => {
            if (err) {
                console.log(err);
                return res.json({code: 2, msg: "服务器错误"});
            }
            return res.json({code: 0});
        });
    });
});
//登录
Router.post("/login", function (req, res) {
    const {userPhone, userPassword} = req.body;
    let sqlQuery = `select phone,password from users where phone=${userPhone}`;
    mysqlConnect.sql(sqlQuery, (err, rows, fields) => {
        if (err) {
            console.log(err);
            return res.json({code: 2, msg: "服务器错误"});
        }
        if (rows.length > 0) {
            if (MD5PWD(userPassword) === rows[0].password) {
                //设置cookie
                res.cookie("userPhone",rows[0].phone);
                return res.json({code: 0});
            } else {
                return res.json({code: 1, msg: "密码错误"});
            }
        } else {
            return res.json({code: 1, msg: "手机号未注册"});
        }
    })
});

//基于MD5 加强加密方式
function MD5PWD(pwd) {
    const rendomWord = "MYNAMEIS-Han~asd*#ASD^^PRO$";
    return utility.md5(utility.md5(pwd + rendomWord));
}

module.exports = Router;

